package whendone

/**
  Miscellaneous helper functions.
  @author Henrik Huttunen
*/
object Helpers{
  import java.io.File
  /** Creates new File with unique name for backuping. */
  def newBackupFileFor(directory: String, file: File): java.io.File = {
    val withoutPostfix = file.getName.substring(0, file.getName.size - ".bin".size)
    new File(directory + File.separator + withoutPostfix + "_" + System.currentTimeMillis + ".bin")    
  }
  /** Whether 'text' endswith 'end' */
  def endsWith(text: String, end: String) = {
    text.lastIndexOf(end) == text.size - end.size
  }
  /** Returns slice of x from min to max. */
  def slice(x: String, min: Int, max: Int) = {
    if(min >= x.size || min >= max) ""
    else if(max >= x.size) x.substring(min, x.size) 
    else x.substring(min, max+1)
  }
  /** All projects in list. */
  def allProjects(parent: Project): List[Project] = {
    parent :: (parent.projects map(allProjects(_)) flatMap(x => x))
  }
  /** Performs cutHeadOffNil for each element in list and yields a new list. */
  def cutHeadOff[a, b](list: List[(a, List[b])]): List[(a, List[b])] = {
    def cutHeadIfNotNil[a, b](list: (a, List[b])) = list._2 match {
      case Nil          => (list._1, Nil)
      case head :: tail => (list._1, tail)
    }  
    list match {
      case Nil          => Nil
      case head :: tail => List(cutHeadIfNotNil(head)) ::: cutHeadOff(tail)
    }
  }
  /** Divides projects into groups where each of group has the same path head in their innermost list */
  def divideProjects(paths: List[(Project, List[String])]) = {
    def divide(paths: List[(Project, List[String])], accumulated: List[List[(Project, List[String])]]): List[List[(Project, List[String])]] = {
      paths match {
        case Nil  => accumulated
        case rest =>
          val (a, b) = rest.partition{case (project, path) => path.head == rest.head._2.head}
          divide(b, accumulated ::: (if(!a.isEmpty) List(a) else Nil))
      }
    }
    divide(paths, Nil)
  }
  /** Creates a string with as many spaces as x size is. */
  def toSpaces(x: String) = List.make(x.size, " ").mkString
  /** Project's path as List(root.name, ..., parent.name, project.name) */
  def nameChain(project: Project): List[String] = project2pathchain(project) map (x => x.name)
  /** Project's path as List(root, ..., parent, project) */
  def project2pathchain(project: Project): List[Project] = {
    def project2pathchain(project: Project, accumulated: List[Project]): List[Project] = project.parent match {
      case None         => List(project) ::: accumulated
      case Some(parent) => project2pathchain(parent, List(project) ::: accumulated)
    }
    project2pathchain(project, Nil)
  }
}